package StudyCode.summary.mycollection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ComputesTheLinearCorrelationBetweenTwoArrays {
	public static void main(String[] argv) {
		double[] v1 = new double[]{34.45, 35.45, 36.67, 37.78, 37.0000,
				37.1234, 67.2344, 68.34534, 69.87700};
		double[] v2 = new double[]{34.45, 35.45, 36.67, 37.78, 37.0000,
				37.1234, 67.2344, 68.34534, 69.87700};
		System.out.println("两个 double 数组的线性相关性是:" + correlation(v1, v2));
	}

	public static double correlation(double[] v1, double[] v2) {
		double denom = Math.sqrt(variance(v1) * variance(v2));
		if (denom != 0)
			return (covariance(v1, v2) / denom);
		else {
			if ((variance(v1) == 0) && (variance(v2) == 0))
				return (1.0);
			else
				return (0.0);
		}
	}

	public static double variance(double[] v) {
		if (v.length > 1) {
			final double m = mean(v);
			double ans = 0.0;
			for (int i = 0; i < v.length; i++)
				ans += (v[i] - m) * (v[i] - m);
			return ans / (v.length - 1);
		} else
			throw new IllegalArgumentException("Array 长度必须是2的倍数.");
	}


	public static double covariance(double[] v1, double[] v2) {
		if (v1.length != v2.length)
			throw new IllegalArgumentException(
					"Arrays 长度必须相同 : " + v1.length + ", " + v2.length);
		final double m1 = mean(v1);
		final double m2 = mean(v2);
		double ans = 0.0;
		for (int i = 0; i < v1.length; i++)
			ans += (v1[i] - m1) * (v2[i] - m2);
		return ans / (v1.length - 1);
	}


	public static double mean(double[] v) {
		return (mass(v) / (double) v.length);
	}

	public static double mass(double[] v) {
		double somme = 0.0;
		for (int k = 0; k < v.length; k++) {
			somme += v[k];
		}
		return (somme);
	}

}
